package com.fzj.ivos_serve.base.exception;

import com.fzj.ivos_serve.base.response.JsonResult;
import com.fzj.ivos_serve.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice//相当于@ResponseBody+@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理服务层异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandleServiceException(ServiceException e){
        String message = e.getStatusCode().getMsg();
        log.error("ServiceException"+message);
        return new JsonResult(e.getStatusCode());
    }

    /**
     * 不合法参数异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e){
        String message = e.getMessage();
        log.error("IllegalArgumentException"+message);
        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }

    /**
     * 运行时异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException e) {
        String message = e.getMessage();
        log.error("RuntimeException: " + message);

        return new JsonResult(StatusCode.OPERATION_FAILED, message);
    }

    /**
     * 1.Spring Validation框架抛出
     * 2.校验POJO类属性时,参数未满足要求.
     * @param ex
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        //Validation中,验证POJO类型参数获取提示消息使用: ex.getFieldError().getDefaultMessage() 方法.
        String message = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException: " + message);

        return new JsonResult(StatusCode.VALIDATE_ERROR, message);
    }

    /**
     * 1.Spring Validation框架抛出;
     * 2.声明参数方式接收数据校验时,参数未满足要求.
     * @param ex
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        // selectById.id: 微博ID必须在200-500之间  ---->  微博ID必须在200-500之间
        String message = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException: " + message);

        return new JsonResult(StatusCode.VALIDATE_ERROR, message);
    }
}
